package com.example.demo.aop;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.demo.annotation.ApiDesc;
import com.example.demo.util.TokenUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @title:	ApiDescAspect
 * @author:	许子文
 * @date:	2025年3月20日 
 * @descirption: 接口描述切面
 *
 */
@Slf4j
@Aspect
@Component
public class ApiDescAspect {
	
	@Pointcut("@annotation(com.example.demo.annotation.ApiDesc)")
	public void addAdvice() {
		
	}
	
	@Before("addAdvice()")
	public void begin(JoinPoint joinPoint) throws NoSuchMethodException, SecurityException {
		log.info("before方法");
		ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
		
		HttpServletRequest request = attributes.getRequest();
		
		Class<?> aClass = joinPoint.getTarget().getClass();//获得所在切点的该类的class对象
		
		String methodName = joinPoint.getSignature().getName();//获得该切点所在的方法的名称
		
		Class<?>[] parameterTypes = ((MethodSignature)joinPoint.getSignature()).getParameterTypes();//拿到方法对应的参数类型
		
		Method method = aClass.getMethod(methodName, parameterTypes);//获取该方法对象
		
		ApiDesc annotion = method.getAnnotation(ApiDesc.class);
		
		String apiDesc = annotion.value();
		
		String token = TokenUtil.getTokenFromRequest(request);
		
		String uri = request.getRequestURI();
		
		log.info("进入【{}】接口>>{},token>>{}",apiDesc,uri,token);
	}
	
}
